//
//  GToolUtil.m
//  iphone


#import "GToolUtil.h"

@implementation GToolUtil

static GToolUtil *sharedInstance = nil;

+ (GToolUtil*) sharedInstance
{
    if (nil == sharedInstance) {
        sharedInstance = [[GToolUtil alloc] init];
    }
	return sharedInstance;
}

- (void)netStatusUpdate:(NetworkStatus)status
{
    _netAvailable = NO;
    switch (status){
        case ReachableViaWWAN:  // 3G
        {
            self.netType = @"3G";
            self.netStatus = @"CONNECTED";
            _netAvailable = YES;
            break;
        }
        case ReachableViaWiFi:
        {
            self.netType = @"Wifi";
            self.netStatus = @"CONNECTED";
            _netAvailable = YES;
            break;
        }
        case ReachableVia2G:
        {
            self.netType = @"2G";
            self.netStatus = @"CONNECTED";
            _netAvailable = YES;
            break;
        }
        case NotReachable:
        {
            self.netType = @"NotReachable";
            self.netStatus = @"DISCONNECTED";
            break;
        }
        default:
            self.netType = @"UnKnow";
            self.netStatus = @"UNKNOWN";
    }
}

- (id)init
{
    self = [super init];
    if (self) {
        _reachability = [[Reachability reachabilityForInternetConnection] retain];
        [_reachability startNotifier];
        [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
        
        [self netStatusUpdate:[_reachability currentReachabilityStatus]];
        
        _dateFormatter = [[NSDateFormatter alloc] init];
        [_dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    }
    return self;
}

- (void)dealloc
{
    [_dateFormatter release];
    [_netType release];
    [_netStatus release];
    [_reachability stopNotifier];
    [_reachability release];
    [super dealloc];
}

- (void)reachabilityChanged:(NSNotification* )note
{
    Reachability* curReach = [note object];
    [self netStatusUpdate:[curReach currentReachabilityStatus]];
}

+(NSString*)urlEscape:(NSString *)unencodedString {
	NSString *s = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
																	  (CFStringRef)unencodedString,
																	  NULL,
																	  (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
																	  kCFStringEncodingGB_18030_2000);
	return [s autorelease];
}

+ (NSString *)urlUnescape: (NSString *) input
{
	NSString *s = (NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                      (CFStringRef)input,
                                                                                      (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                                      kCFStringEncodingGB_18030_2000);
	return [s autorelease];
}

// Put a query string onto the end of a url
+(NSString*)addQueryStringToUrl:(NSString *)url params:(NSDictionary *)params
{
	NSMutableString *urlWithQuerystring = [[[NSMutableString alloc] initWithString:url] autorelease];
	// Convert the params into a query string
	if (params) {
		for(id key in params) {
			NSString *sKey = [key description];
			NSString *sVal = [[params objectForKey:key] description];
			// Do we need to add ?k=v or &k=v ?
			if ([urlWithQuerystring rangeOfString:@"?"].location==NSNotFound) {
				[urlWithQuerystring appendFormat:@"?%@=%@", [GToolUtil urlEscape:sKey], [GToolUtil urlEscape:sVal]];
			} else {
				[urlWithQuerystring appendFormat:@"&%@=%@", [GToolUtil urlEscape:sKey], [GToolUtil urlEscape:sVal]];
			}
		}
	}
    
	return urlWithQuerystring;
}

+(NSString*)dateStrFromDataFormat:(long long)time
{
    NSString * str = [NSString stringWithFormat:@"%lld", time];
    NSDate * myDate = [[GToolUtil sharedInstance].dateFormatter dateFromString:str];
    
    NSString * strRet = nil;
    if (myDate) {
        const unsigned int unitFlags = NSMinuteCalendarUnit | NSHourCalendarUnit | NSDayCalendarUnit
        | NSWeekCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;
        NSDateComponents * dateInfo = [[NSCalendar currentCalendar] components:unitFlags fromDate:myDate toDate:[NSDate date] options:0];
        
        if ([dateInfo year] > 0) {
            strRet = [NSString stringWithFormat:@"%d年前", [dateInfo year]];
        } else if ([dateInfo month] > 0) {
            strRet = [NSString stringWithFormat:@"%d月前", [dateInfo month]];
        } else if ([dateInfo week] > 0) {
            strRet = [NSString stringWithFormat:@"%d周前", [dateInfo week]];
        } else if ([dateInfo day] > 0) {
            strRet = [NSString stringWithFormat:@"%d天前", [dateInfo day]];
        } else if ([dateInfo hour] > 0) {
            strRet = [NSString stringWithFormat:@"%d小时前", [dateInfo hour]];
        } else if ([dateInfo minute] > 0) {
            strRet = [NSString stringWithFormat:@"%d分钟前", [dateInfo minute]];
        } else {
            strRet = @"刚刚";
        }
    }
    
    return strRet;
}

+(NSString*)dateStrFromDataFormat2:(long long)time
{
    NSString * str = [NSString stringWithFormat:@"%lld", time];
    NSDate * myDate = [[GToolUtil sharedInstance].dateFormatter dateFromString:str];
    
    NSString * strRet = nil;
    if (myDate) {
        const unsigned int unitFlags = NSSecondCalendarUnit | NSMinuteCalendarUnit | NSHourCalendarUnit | NSDayCalendarUnit
        | NSWeekCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;
        NSDateComponents * dateInfo = [[NSCalendar currentCalendar] components:unitFlags fromDate:myDate toDate:[NSDate date] options:0];
        
        if ([dateInfo year] != 0) {
            if ([dateInfo year] > 0) {
                strRet = [NSString stringWithFormat:@"%d年前", [dateInfo year]];
            } else {
                strRet = [NSString stringWithFormat:@"%d年后", -[dateInfo year]];
            }
        } else if ([dateInfo month] != 0) {
            if ([dateInfo month] > 0) {
                strRet = [NSString stringWithFormat:@"%d月前", [dateInfo month]];
            } else {
                strRet = [NSString stringWithFormat:@"%d月后", -[dateInfo month]];
            }
        } else if ([dateInfo week] != 0) {
            if ([dateInfo week] > 0) {
                strRet = [NSString stringWithFormat:@"%d周前", [dateInfo week]];
            } else {
                strRet = [NSString stringWithFormat:@"%d周后", -[dateInfo week]];
            }
        } else if ([dateInfo day] != 0) {
            if ([dateInfo day] > 0) {
                strRet = [NSString stringWithFormat:@"%d天前", [dateInfo day]];
            } else {
                strRet = [NSString stringWithFormat:@"%d天后", -[dateInfo day]];
            }
        } else if ([dateInfo hour] != 0) {
            if ([dateInfo hour] > 0) {
                strRet = [NSString stringWithFormat:@"%d小时前", [dateInfo hour]];
            } else {
                strRet = [NSString stringWithFormat:@"%d小时后", -[dateInfo hour]];
            }
        } else if ([dateInfo minute] != 0) {
            if ([dateInfo minute] > 0) {
                strRet = [NSString stringWithFormat:@"%d分钟前", [dateInfo minute]];
            } else {
                strRet = [NSString stringWithFormat:@"%d分钟后", -[dateInfo minute]];
            }
        } else {
            if ([dateInfo minute] > 0) {
                strRet = @"刚刚";
            } else {
                strRet = @"马上";
            }
        }
    }
    
    return strRet;
}

+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,181
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0125-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+ (long long)NSDateToFPDate:(NSDate*)date
{
    if (nil == date) {
        return 0;
    }
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:date];
    
    long long year = [dateComponent year];
    long long month = [dateComponent month];
    long long day = [dateComponent day];
    long long hour = [dateComponent hour];
    long long minute = [dateComponent minute];
    long long second = [dateComponent second];
    
    long long retTime = (year*10000 + month*100 + day) * 1000000;
    retTime += (hour*10000 + minute*100 + second);
    
    return retTime;
}

+ (NSMutableArray*)PBArr2NSArr:(PBArray*)array
{
    NSMutableArray * retArr = [[[NSMutableArray alloc] initWithCapacity:array.count] autorelease];
    for (int i = 0; i < array.count; i++) {
        [retArr addObject:[array objectAtIndex:i]];
    }
    return retArr;
}

+ (UserMessage*)ownerMsg
{
    long long selfId = [GConfig getUserId];
    NSDictionary * selfInfo = [GConfig getUserLoginInfo];
    NSString * phone = [selfInfo objectForKey:@"phone"];
    
    if (selfId > 0 && phone.length > 0) {
        return [[[[UserMessage builder] setId:selfId] setPhone:phone] build];
    }
    
    return nil;
}

+ (NSString*) stringBySeconds:(NSInteger)seconds
{
    NSInteger minuteBefore = seconds/60;
    NSInteger hourBefore = minuteBefore/60;
    NSInteger dayBefore = hourBefore/24;
    if (dayBefore > 0) {
        return [NSString stringWithFormat:@"%d天%d时%d分", dayBefore, hourBefore%24, minuteBefore%60];
    } else if (hourBefore > 0) {
        return [NSString stringWithFormat:@"%d时%d分", hourBefore, minuteBefore%60];
    } else {
        return [NSString stringWithFormat:@"%d分钟", minuteBefore];
    }
    return @"";
}

@end